package com.springboot.demo.event;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 监听器类被标记为@Component,Spring会自动扫描并加载它
 *
 * 监听器实现了ApplicationListener接口，可以监听ApplicationEvent事件
 *
 * 当发布UserRegisterEvent事件时，Spring会调用所有ApplicationListener的onApplicationEvent方法
 *
 * 这个监听器的supportsEventType方法返回true,表示它支持UserRegisterEvent事件
 *
 * 所以它的onApplicationEvent方法就会被调用，实现具体的监听逻辑
 */
@Component
public class SmartUserRegisterListener implements SmartApplicationListener {
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        if (aClass == UserRegisterEvent.class){
            System.out.println(aClass);
            System.out.println(UserRegisterEvent.class);
            return true;
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        UserRegisterEvent event = (UserRegisterEvent) applicationEvent;
        System.out.println("监听事件触发");
        System.out.println(event.getUser().getUsername());

    }
}
